package com.ylz.sjzx.sio.common.core.core.container;

import com.ylz.sjzx.sio.common.core.core.IAdapter;
import com.ylz.sjzx.sio.common.core.core.container.common.BaseScanner;
import com.ylz.sjzx.sio.common.core.core.container.common.annotation.AdapterDesc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.Set;

/**
 * 容器扫描器.
 * 提供API自动扫描项目内部指定class子类,
 * 并获得对应的初始化对象list.
 */
class ContainerScanner extends BaseScanner {

    private static final Logger logger =
            LoggerFactory.getLogger(ContainerScanner.class);

    /**
     * 扫描Adapter组件，Adapter必须有AdapterDesc注解，否则忽略。
     *
     * @return Set<IAdapter>
     */
    static Set<IAdapter> scanAdapter() {
        Set<IAdapter> adapters = new HashSet<>();
        Set<Class<?>> classSet = BaseScanner.scan(IAdapter.class);
        if (classSet != null) {
            for (Class<?> classObj : classSet) {
                AdapterDesc config = classObj.getAnnotation(AdapterDesc.class);
                if (config != null) {
                    try {
                        adapters.add((IAdapter) classObj.getDeclaredConstructor().newInstance());
                    } catch (Exception e) {
                        logger.error("scanAdapter error for {} : {}", classObj, e);
                    }
                }
            }
        }
        return adapters;
    }

}
